<template>
  <px-dialog v-model="visible" class="tool-dialog" title="归还工具" width="1200px" @open="openDialog" @close="closeDialog">
    <div>
      <px-scrollbar v-if="isShowDetail" class="view-equip-detail" max-height="350px" style="margin-bottom: 10px">
        <div class="view-equip-wrap">
          <div class="view-equip-content">
            <div class="view-equip-item">
              <div class="label">工具借用单号</div>
              <div class="text">{{ detailData.toolBorrowCode }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">工具编码</div>
              <div class="text">{{ detailData.toolCode }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">工具名称</div>
              <div class="text">{{ detailData.toolName }}</div>
            </div>
          </div>
          <div class="view-equip-content">
            <div class="view-equip-item">
              <div class="label">工具分类</div>
              <div class="text">{{ detailData.toolCategoryDesc }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">型号/规格</div>
              <div class="text">{{ detailData.toolModel }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">品牌</div>
              <div class="text">{{ detailData.brandVal }}</div>
            </div>
          </div>
          <div class="view-equip-content">
            <div class="view-equip-item">
              <div class="label">工具单位</div>
              <div class="text">{{ detailData.toolUnitDesc }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">资产标签</div>
              <div class="text">{{ detailData.assetTagDesc }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">工具科室</div>
              <div class="text">{{ detailData.classNameDesc }}</div>
            </div>
          </div>
          <div class="view-equip-content">
            <div class="view-equip-item">
              <div class="label">工具管理人</div>
              <div class="text">{{ detailData.custodianName }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">借用人</div>
              <div class="text">{{ detailData.toolBorrowerName }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">借用人电话</div>
              <div class="text">{{ detailData.toolBorrowerPhone }}</div>
            </div>
          </div>
          <div class="view-equip-content">
            <div class="view-equip-item">
              <div class="label">借出操作人</div>
              <div class="text">{{ detailData.updateName }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">借用时间</div>
              <div class="text">{{ detailData.toolBorrowDate }}</div>
            </div>
            <div class="view-equip-item">
              <div class="label">借出用途</div>
              <div class="text">{{ detailData.toolBorrowUse }}</div>
            </div>
          </div>
          <div class="view-equip-content">
            <div class="view-equip-item plus">
              <div class="label">归还状态</div>
              <div class="text">
                <px-tag
                  effect="plain"
                  :style="{
                    color: 'rgba(0, 0, 0, 0.8)',
                    border: `1px solid ${detailData.revertStatus === 1 ? '#4CCBA1' : '#F7B648'}`,
                    backgroundColor: `${detailData.revertStatus === 1 ? '#E8F8F3' : '#FEF5E6'}`
                  }"
                >
                  {{ detailData.revertStatusDesc }}
                </px-tag>
              </div>
            </div>
          </div>
        </div>
      </px-scrollbar>
      <px-form ref="formRef" class="tool-dialog-form" :model="formValue" :rules="rules" label-position="right" label-width="100px">
        <px-form-item label="归还人" prop="toolReverter">
          <px-select-v2
            v-model="formValue.toolReverter"
            style="width: 100%"
            filterable
            clearable
            :options="peopleList"
            placeholder="请选择归还人"
            @change="principalChange"
          />
        </px-form-item>
        <px-form-item v-if="isSimple" label="备注" prop="remark">
          <px-input v-model="formValue.remark" type="textarea" placeholder="请输入备注" maxlength="1000" :autosize="{ minRows: 2, maxRows: 4 }" />
        </px-form-item>
      </px-form>
      <div style="margin-top: 16px; text-align: right">
        <px-button @click="closeDialog">取消</px-button>
        <px-button type="primary" @click="handleSubmit(formRef)">确认</px-button>
      </div>
    </div>
  </px-dialog>
</template>
<script setup lang="ts">
import { batchToolReturn, queryToolLoanList } from "@/api/equip/toolManage";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { PxMessage } from "px-ui";
import { computed, reactive, toRefs } from "vue";

// 调用父级-查询主页列表、关闭弹窗方法
const emits = defineEmits(["queryTable", "closeDialog"]);
// 父级传过来的值
const props = defineProps({
  // 控制弹窗显示隐藏
  visible: {
    type: Boolean,
    default: false
  },
  // 区分单个还是批量归还
  isSimple: {
    type: Boolean,
    default: false
  },
  // 区分是不是要展示头部的详情内容
  isShowDetail: {
    type: Boolean,
    default: false
  },
  // 工具台账id
  toolId: {
    type: [Number, Array],
    default() {
      return undefined;
    }
  },
  rowData: {}
});
const visible = computed(() => props.visible);
// 页面本身的值
const state = reactive<any>({
  formRef: null,
  detailData: {},
  formValue: {
    toolReverter: null
  },
  peopleList: [] // 归还人列表
});
const { formRef, detailData, formValue, peopleList } = toRefs(state);
const rules = computed(() => ({
  toolReverter: [{ required: true, message: "归还人不能为空", trigger: ["blur", "change"] }]
}));

// 获取归还人的名字
const principalChange = val => {
  const arr = peopleList.value.filter(item => {
    return item.value === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.toolReverterName = arr[0].label;
  }
};

// 提交-确定工具归还
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      let borrowId = [];
      if (props.isShowDetail) {
        borrowId = [detailData.value.id];
      } else {
        borrowId = Array.isArray(props.toolId) ? props.toolId : [props.toolId];
      }
      await batchToolReturn({
        ids: borrowId,
        ...formValue.value
      });
      PxMessage.success("工具归还成功!");
      emits("closeDialog");
      emits("queryTable");
    }
  });
};
// 打开弹窗
const openDialog = async () => {
  formRef.value.resetFields();
  peopleList.value = await getEmployeeIdAndName(["MACHINE", "WATER", "GAS", "ELECTRICTITY"]);
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  // 如果当前登录人在下拉列表里则给他默认值
  const filterItem = peopleList.value?.filter(item => item.userId === userInfo?.userId);
  if (filterItem?.length !== 0) {
    formValue.value.toolReverter = userInfo?.userId;
    formValue.value.toolReverterName = filterItem[0]?.label;
  }
  if (props.isShowDetail) {
    const res = await queryToolLoanList({ toolCode: props.rowData.toolCode, revertStatus: 2, pageNum: 1, pageSize: 20 });
    detailData.value = res?.data[0] || {};
  }
};
// 查询列表关闭弹窗
const closeDialog = (val?: any) => {
  formRef.value.resetFields();
  emits("closeDialog");
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/view-detail.scss");
.view-equip-detail {
  height: auto;
  padding: 0;
  padding-left: 24px;
}
</style>
